package com.shangrila.biz.open.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.shangrila.biz.category.SellerCredit;
import com.shangrila.biz.domain.TaokeItem;
import com.shangrila.biz.open.TaobaoApiException;
import com.shangrila.biz.open.TaobaoResult;
import com.shangrila.biz.open.service.TaobaoPlatform;
import com.shangrila.biz.open.utils.TaobaoPlatformHelper;
import com.shangrila.common.lang.Money;
import com.taobao.api.ApiException;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.ItemImg;
import com.taobao.api.domain.ItemProp;
import com.taobao.api.domain.PromotionDisplayTop;
import com.taobao.api.domain.TaobaokeItem;
import com.taobao.api.domain.TaobaokeItemDetail;
import com.taobao.api.request.ItemGetRequest;
import com.taobao.api.request.ItempropsGetRequest;
import com.taobao.api.request.ItemsListGetRequest;
import com.taobao.api.request.TaobaokeItemsCouponGetRequest;
import com.taobao.api.request.TaobaokeItemsDetailGetRequest;
import com.taobao.api.request.UmpPromotionGetRequest;
import com.taobao.api.response.ItemGetResponse;
import com.taobao.api.response.ItempropsGetResponse;
import com.taobao.api.response.ItemsListGetResponse;
import com.taobao.api.response.TaobaokeItemsCouponGetResponse;
import com.taobao.api.response.TaobaokeItemsDetailGetResponse;
import com.taobao.api.response.UmpPromotionGetResponse;

public class DefaultTaobaoPlatform implements TaobaoPlatform{

	private final static String ITEM_FIELDS = "detail_url,num_iid,title,nick,type,cid,seller_cids,props,input_pids,input_str,desc,pic_url,num,valid_thru,list_time,delist_time,stuff_status,location,price,post_fee,express_fee,ems_fee,has_discount,freight_payer,has_invoice,has_warranty,has_showcase,modified,increment,approve_status,postage_id,product_id,auction_point,property_alias,item_img,prop_img,sku,video,outer_id,is_virtual";
	private final static String ITEMLIST_FIELDS = "detail_url,num_iid,title,nick,cid,props,input_str,pic_url,num,list_time,delist_time,stuff_status,location,price,post_fee,express_fee,ems_fee,has_discount,freight_payer,has_invoice,has_warranty,modified,approve_status,postage_id,auction_point,property_alias,item_img,sku,is_virtual";
	
	private final static String TAOKE_ITEMS_DETAIL_FIELDS = "click_url,title,price,num_iid,nick,pic_url,item_img.url";
	private final static String TAOKE_USER_NICK = "kalman03";
	private final static String TAOKE_OUTCODE = "12xiaoshi";
	@Autowired
	private TaobaoClient taobaoClient;
	
	@Override
	public TaobaoResult<Item> getItem(long itemId) throws TaobaoApiException {
		TaobaoResult<Item> result = new TaobaoResult<Item>(false);
		try {
			ItemGetRequest request = new ItemGetRequest();
			request.setNumIid(itemId);
			request.setFields(ITEM_FIELDS);
			ItemGetResponse response = taobaoClient.execute(request);
			if(response != null && response.isSuccess()){
				Item item = response.getItem();
				result.setResult(item);
				result.setSuccess(true);
			}else{
				TaobaoPlatformHelper.doErrorMsg(response, result);
			}
		} catch (ApiException e) {
			throw new TaobaoApiException(e);
		}
		return result;
	}

	@Override
	public TaobaoResult<List<Item>> getItemList(Set<Long> itemIds)
			throws TaobaoApiException {
		TaobaoResult<List<Item>> result = new TaobaoResult<List<Item>>(false);
		try {
			ItemsListGetRequest request=new ItemsListGetRequest();
			request.setFields(ITEMLIST_FIELDS);
			String numIids = TaobaoPlatformHelper.getItemIdsStr(itemIds);
			request.setNumIids(numIids);
			ItemsListGetResponse response = taobaoClient.execute(request);
			if(response != null && response.isSuccess()){
				result.setResult(response.getItems());
				result.setSuccess(true);
			}else{
				TaobaoPlatformHelper.doErrorMsg(response, result);
			}
		} catch (Exception e) {
			throw new TaobaoApiException(e);
		}
		return result;
	}

	@Override
	public TaobaoResult<List<ItemProp>> getPropertyList(long leafCatId)throws TaobaoApiException {
		TaobaoResult<List<ItemProp>> result = new TaobaoResult<List<ItemProp>>(false);
		try {
			ItempropsGetRequest request=new ItempropsGetRequest();
			request.setFields("is_input_prop,pid,name,must,multi,prop_values");
			request.setCid(leafCatId);
			ItempropsGetResponse response = taobaoClient.execute(request);
			if(response != null && response.isSuccess()){
				result.setResult(response.getItemProps());
				result.setSuccess(true);
			}else{
				TaobaoPlatformHelper.doErrorMsg(response, result);
			}
		} catch (Exception e) {
			throw new TaobaoApiException(e);
		}
		return result;
	}

	@Override
	public TaobaoResult<List<TaokeItem>> getTaokeItemList(Set<Long> itemIds)throws TaobaoApiException {
		TaobaoResult<List<TaokeItem>> result = new TaobaoResult<List<TaokeItem>>(false);
		if(CollectionUtils.isEmpty(itemIds)){
			return result;
		}
		try {
			List<TaokeItem> taokeItems = new ArrayList<TaokeItem>();
			TaobaokeItemsDetailGetRequest taobaokeItemsDetailGetRequest = new TaobaokeItemsDetailGetRequest();
			taobaokeItemsDetailGetRequest.setFields(TAOKE_ITEMS_DETAIL_FIELDS);
			taobaokeItemsDetailGetRequest.setNick(TAOKE_USER_NICK);
			String ids = TaobaoPlatformHelper.getItemIdsStr(itemIds);
			taobaokeItemsDetailGetRequest.setNumIids(ids);
			taobaokeItemsDetailGetRequest.setOuterCode(TAOKE_OUTCODE);
			TaobaokeItemsDetailGetResponse  taobaokeItemsDetailGetResponse = taobaoClient.execute(taobaokeItemsDetailGetRequest);
			if(taobaokeItemsDetailGetResponse != null && taobaokeItemsDetailGetResponse.isSuccess()){
				for(long itemId : itemIds){
					PromotionDisplayTop promotionDisplayTop = getItemPromotion(itemId);
					TaokeItem taokeItem = getTaokeItem(itemId,promotionDisplayTop, taobaokeItemsDetailGetResponse);
					if(taokeItem != null){
						taokeItems.add(taokeItem);
					}
				}
			}else{
				TaobaoPlatformHelper.doErrorMsg(taobaokeItemsDetailGetResponse, result);
			}
			if(CollectionUtils.isNotEmpty(taokeItems)){
				result.setSuccess(true);
				result.setResult(taokeItems);
			}
		} catch (Exception e) {
			throw new TaobaoApiException(e);
		}
		return result;
	}
	
	private TaokeItem getTaokeItem(long itemId,PromotionDisplayTop promotionDisplayTop,TaobaokeItemsDetailGetResponse taobaokeItemsDetailGetResponse){
		List<TaobaokeItemDetail> taobaokeItemDetailList = taobaokeItemsDetailGetResponse.getTaobaokeItemDetails();
		if( CollectionUtils.isNotEmpty(taobaokeItemDetailList) && promotionDisplayTop != null){
			TaokeItem taokeItem  = new TaokeItem();
			taokeItem.setPromotionInItemList(promotionDisplayTop.getPromotionInItem());
			taokeItem.setPromotionInShopList(promotionDisplayTop.getPromotionInShop());
			for(TaobaokeItemDetail itemDetail : taobaokeItemDetailList){
				Item item = itemDetail.getItem();
				if(item.getNumIid().compareTo(itemId) == 0){
					taokeItem.setItemId(itemId);
					taokeItem.setPrice(new Money(item.getPrice()));
					taokeItem.setSellerNick(item.getNick());
					taokeItem.setTitle(item.getTitle());
					
					taokeItem.setTaokeUrl(itemDetail.getClickUrl());
					taokeItem.setShopUrl(itemDetail.getShopClickUrl());
					taokeItem.setSellerCreditScore(itemDetail.getSellerCreditScore());
					taokeItem.setMainPicUrl(item.getPicUrl());
					List<ItemImg> itemImgs = item.getItemImgs();
					taokeItem.setPicList(TaobaoPlatformHelper.getPicUrlList(itemImgs));
					break;
				}
			}
			return taokeItem;
		}
		return null;
	}
	
	
//	public List<TaobaokeItemDetail> getTaobaokeItemDetail(Set<Long> itemIds) throws TaobaoApiException {
//		if(CollectionUtils.isEmpty(itemIds)){
//			return null;
//		}
//		try {
//			TaobaokeItemsDetailGetRequest request = new TaobaokeItemsDetailGetRequest();
//			request.setFields(TAOKE_ITEMS_DETAIL_FIELDS);
//			request.setNick(TAOKE_USER_NICK);
//			request.setNumIids(getItemIdsStr(itemIds));
//			request.setOuterCode(TAOKE_OUTCODE);
//			TaobaokeItemsDetailGetResponse  response = taobaoClient.execute(request);
//			if(response != null && response.isSuccess()){
//				return response.getTaobaokeItemDetails();
//			}else{
//				TaobaoResultHelper.doErrorMsg(response);
//			}
//			return null;
//		} catch (Exception e) {
//			throw new TaobaoApiException(e);
//		}
//	}
//	
	public PromotionDisplayTop getItemPromotion(long itemId) throws TaobaoApiException{
		try {
			UmpPromotionGetRequest req=new UmpPromotionGetRequest();
			req.setItemId(itemId);
			//req.setChannelKey(TAOKE_OUTCODE);
			UmpPromotionGetResponse response = taobaoClient.execute(req );
			if(response != null && response.isSuccess()){
				return response.getPromotions();
			}else{
				TaobaoPlatformHelper.doErrorMsg(response);
			}
			return null;
		} catch (Exception e) {
			throw new TaobaoApiException(e);
		}
	}
	
	@Override
	public TaobaoResult<List<TaokeItem>> getTaokeItemList(int count,long catId,String q) throws TaobaoApiException {
		try {
			TaobaoResult<List<TaokeItem>> result = new TaobaoResult<List<TaokeItem>>(false);
			
			List<TaobaokeItem> taobaokeItemList = new ArrayList<TaobaokeItem>();
			if(count >20 ){
				int a = count % 20;
				int b = count / 20;
				for(int i=1;i<=(b+1);i++){
					TaobaokeItemsCouponGetRequest request = initTaobaokeItemsCouponGetRequest(i, 20, catId,q);
					List<TaobaokeItem> coll = doTaobaokeItemsCouponRequest(request);
					if(CollectionUtils.isNotEmpty(coll)){
						if(i == (b+1)){
							for(int y=0;y<a;y++){
								taobaokeItemList.add(coll.get(y));
							}
						}else{
							taobaokeItemList.addAll(coll);
						}
					}
				}
			}else{
				TaobaokeItemsCouponGetRequest request = initTaobaokeItemsCouponGetRequest(1, count, catId,q);
				taobaokeItemList = doTaobaokeItemsCouponRequest(request);
			}
			if(CollectionUtils.isNotEmpty(taobaokeItemList)){
				List<Long> itemIds = new ArrayList<Long>();
				for(TaobaokeItem item : taobaokeItemList){
					itemIds.add(item.getNumIid());
				}
				List<Item> items = getItemImages(itemIds);
				List<TaokeItem> taokeItems = TaobaoPlatformHelper.convert(taobaokeItemList, items);
				if(CollectionUtils.isNotEmpty(taokeItems)){
					result.setSuccess(true);
					result.setResult(taokeItems);
				}
			}
			return result;
		} catch (Exception e) {
			throw new TaobaoApiException(e);
		}
	}
	
	public static void main(String[] args) {
		System.out.println(119/20);
		System.out.println(119%20);
	}
	
	private List<TaobaokeItem> doTaobaokeItemsCouponRequest(TaobaokeItemsCouponGetRequest request) throws ApiException{
		TaobaokeItemsCouponGetResponse response = taobaoClient.execute(request);
		if(response != null && response.isSuccess()){
			return response.getTaobaokeItems();
		}
		TaobaoPlatformHelper.doErrorMsg(response);
		return null;
	}
	
	private TaobaokeItemsCouponGetRequest initTaobaokeItemsCouponGetRequest(int pageNo,int pageSize,long catId,String q){
		TaobaokeItemsCouponGetRequest req = new TaobaokeItemsCouponGetRequest();
		if(StringUtils.isNotBlank(q)){
			req.setKeyword(q);
		}
		req.setNick("陈丽_chris");
		req.setOuterCode("12xiaoshi");
		//req.setCouponType(1L);//FIXME 南江
		req.setCid(catId);
		req.setShopType("all");
		req.setSort("commissionRate_desc");
//		CouponPriceRateEnum couponPriceRateEnum = CouponPriceRateEnum.get(catId);
//		if(couponPriceRateEnum != null){
			req.setStartCouponRate(7000L);
//		}
		req.setStartCredit(SellerCredit._4diamond.getKey());
		req.setEndCredit(SellerCredit._5goldencrown.getKey());
		req.setStartCommissionRate(1500L);
//		req.setEndCommissionRate(null);
//		req.setStartCommissionVolume(null);
//		req.setEndCommissionVolume(null);
		req.setStartCommissionNum(15L);
//		req.setEndCommissionNum(null);
		req.setStartVolume(5L);
//		req.setEndVolume(null);
//		req.setArea(null);
		req.setFields("num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume,coupon_price,coupon_rate,coupon_start_time,coupon_end_time,shop_type");
		req.setPageNo(new Long(pageNo));
		req.setPageSize(new Long(pageSize));
		return req;
	}
	
	@Override
	public List<Item> getItemImages(List<Long> itemIds) throws TaobaoApiException{
		if(itemIds !=null && itemIds.size() >0){
			try {
				List<Item> result = new ArrayList<Item>();
				if(itemIds.size() <= 20){
					doTaobaoImagesInvoke(itemIds, result);
				}else{
					int count = itemIds.size();
					int index = 0;
					Set<Long> itemIdSet = new TreeSet<Long>();
					for(int i =0 ;i< count ;i++){
						itemIdSet.add(itemIds.get(i));
						index ++;
						if(index == 20){
							doTaobaoImagesInvoke(itemIdSet, result);
							itemIdSet = new TreeSet<Long>();
							index = 0;
						}else if(i == count -1){
							doTaobaoImagesInvoke(itemIdSet, result);
							itemIdSet = null;
						}
					}
				}
				return result;
			} catch (Exception e) {
				throw new TaobaoApiException(e);
			}
		}
		return null;
	}

	private void doTaobaoImagesInvoke(Collection<Long> itemIds, List<Item> result)
			throws ApiException {
		ItemsListGetRequest request=new ItemsListGetRequest();
		request.setFields("num_iid,item_img,pic_url");
		String numIids = TaobaoPlatformHelper.getItemIdsStr(itemIds);
		request.setNumIids(numIids);
		ItemsListGetResponse response = taobaoClient.execute(request);
		if(response != null && response.isSuccess()){
			if(response.getItems() != null){
				result.addAll(response.getItems());
			}
		}else{
			TaobaoPlatformHelper.doErrorMsg(response);
		}
	}
}
